<?php


namespace Beerus\Modules\Album\Controllers;

use hhz\constant\redis\redisKeys;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\album\AlbumRecommendCache;
use Biz\model\Album\AlbumListModel;
use Biz\model\Album\AlbumRelateTagsModel;
use Biz\model\wiki\Wiki as mWiki;
use Biz\service\Album\AlbumListService;
use Biz\service\GoodsTestActivity\FineGoodsService;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Exception;
use Hhz\Redis\newCache;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class AlbumIndexController extends Controller
{
    const PAGE_SIZE = 20;


    public function index(Request $request, Content $content)
    {
        Admin::script($this->indexScript());
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        if ($request->input('status') == NULL) {
            $request->merge([
                'status' => AlbumListModel::STATUS_SUCCESS
            ]);
        }
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize,

        ];
        $where['uid'] = AlbumListModel::DEFAULT_UID_HAOHAOZHU;
        $where['LIMIT'] = $limit;
        $where['ORDER'] = ['id'=>'DESC'];
        // 处理查询条件
        $condition = $this->getCondition($request->all());
        if ($condition) {
            $where = array_merge($where, $condition);
        }

        $list = AlbumListModel::selectByWhere($where);
        unset($where['LIMIT']);
        $total = AlbumListModel::count($where);

        //查询标签列表
        $tagList = AlbumListService::getTagList();
        $tagArr = [];
        if ($tagList) {
            foreach ($tagList as $tag) {
                $tagArr[] = explode('|', $tag)[1];
            }
        }

        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $tagArr) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableCreateButton();
            $grid->filter(function (Grid\Filter $filter) use ($tagArr) {
                $filter->disableIdFilter();
                $filter->expand();//默认展开
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('album_id', '清单ID');
                    $filter->equal('title', '清单名称');
                    $filter->date('publish_time', '发布时间');
                });
                $filter->column(1 / 3, function (Grid\Filter $filter) use ($tagArr) {
                    $filter->equal('status', '清单状态')->select(AlbumListModel::STATUS_MAP);
                    $filter->equal('tag_name', '标签')->select(array_combine($tagArr, $tagArr));
                });
            });

            $grid->column('id', '自增ID');
            $grid->column('album_id', '清单ID')->copyable();
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('cover_img', '封面图')->display(function ($coverImg) {

                return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'800px\', \'800px\'],content: \''.$coverImg.'\'});">
                                <img width="100px" height="100px" src="'.$coverImg.'">
                            </a>';
            });
            $grid->column('title', '清单名称')->copyable();
            $grid->column('desc', '清单描述');
            $grid->column('wiki_count', '商品数量');
            $grid->column('tags', '标签');
            $grid->column('status_name', '状态')->label([
                AlbumListModel::STATUS_MAP[AlbumListModel::STATUS_UNTREATED] => 'default',
                AlbumListModel::STATUS_MAP[AlbumListModel::STATUS_USER_PRIVATE] => 'warning',
                AlbumListModel::STATUS_MAP[AlbumListModel::STATUS_DRAFT] => 'info',
                AlbumListModel::STATUS_MAP[AlbumListModel::STATUS_SUCCESS] => 'success',
            ]);
            $grid->column('publish_time_string', '发布时间');
            $grid->column('edittime', '更新时间');
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
            });
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('&nbsp;&nbsp;<a class="fa" href="'.url('admin/album/index/create?album_id='.$actions->row->album_id).'">编辑</a>');
                if ($actions->row->status == AlbumListModel::STATUS_SUCCESS) {
                    $actions->append('&nbsp;&nbsp;<a class="act fa self-visible" href="javascript:;"  data-album_id="'.$actions->row->album_id.'" data-action="self-visible">仅自己可见</a>');
                }
                if ($actions->row->status == AlbumListModel::STATUS_USER_PRIVATE) {
                    $actions->append('&nbsp;&nbsp;<a class="act fa all-public" href="javascript:;"  data-album_id="'.$actions->row->album_id.'" data-action="all-public">全员可见</a>');
                }
                $actions->append('&nbsp;&nbsp;<a class="act fa del-album" href="javascript:;"  data-album_id="'.$actions->row->album_id.'" data-action="del-album">删除</a>');



            });

        });

        $tab = new Tab();
        $tab->add('官方清单管理', $grid->render(), true);
        $tab->addLink('创建清单', url("/admin/album/index/create"), false);
        $content->row($tab);

        return $content
            ->header("发现好物 | 官方清单管理")
            ->description(' ')
            ->breadcrumb(['text' => '审核列表', 'url' => '/album/index'], ['text' => '官方清单管理']);
    }

    private function indexScript()
    {
        return <<<EOF
        $('.self-visible').unbind('click').click(function() {
            var album_id = $(this).data('album_id');
            let act= $(this).data('action');
            swal({
                title: "确认设置为仅自己可见吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'post',
                        url: '/admin/album/index/act?album_id=' + album_id+'&act='+act,
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });
        
        $('.all-public').unbind('click').click(function() {
            var album_id = $(this).data('album_id');
            let act= $(this).data('action');
            swal({
                title: "确认设置为全员可见吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'post',
                        url: '/admin/album/index/act?album_id=' + album_id+'&act='+act,
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });
        $('.del-album').unbind('click').click(function() {
            var album_id = $(this).data('album_id');
            let act= $(this).data('action');
            swal({
                title: "确认要删除吗，此操作不可逆!!!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'post',
                        url: '/admin/album/index/act?album_id=' + album_id+'&act='+act,
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });
EOF;
    }

    public function getCondition($request)
    {
        $condition = [];
        if (isset($request['title']) && !empty($request['title'])) {
            $condition['title[~]'] = $request['title'];
        }
        if (isset($request['album_id']) && !empty($request['album_id'])) {
            $condition['album_id'] = $request['album_id'];
        }
        if (isset($request['publish_time']) && !empty($request['publish_time'])) {
            $publishTime = strtotime($request['publish_time']);
            $condition['publish_time[<>]'] = [$publishTime,$publishTime + 60*60*24];
        }
        if (isset($request['status'])) {
            $condition['status'] = $request['status'];
        }
        if (isset($request['tag_name']) && !empty($request['tag_name'])) {
            $albumIds = AlbumRelateTagsModel::selectByWhere([
                'tag_name' => $request['tag_name'],
                'status' => AlbumRelateTagsModel::STATUS_NORMAL,
            ], 'album_id');
            $condition['album_id'] = $albumIds;
        }
        return $condition;
    }

    public function create(Content $content, Request $request): Content
    {
        $albumId = $request->input('album_id');
        $data = [];
        $title = '创建清单';
        if ($albumId) {
            $data = AlbumListService::getAlbumInfo($albumId);
            $title = '编辑清单';
        }
        $tagList = AlbumListService::getTagList();
        $form = new Form($data);
        $form->hidden('album_id');
        $form->text('title', '清单名称')->required()->placeholder('最多可输入20个字')->help('最多可输入20个字');
        if($data && is_array($data)){
            $form->select('uid', "官方账户")->options(AlbumListModel::OFFICIAL_UID_MAP)->readOnly();

        }else{
            $form->select('uid', "官方账户")->options(AlbumListModel::OFFICIAL_UID_MAP)->required();
        }


        $form->text('desc', '清单描述')->required()->placeholder('最多支持配置1000字')->help('最多支持配置1000字');
        $form->imgUpload('cover_img', '清单封面图', false, [
            'isUpload' => true,
            'isGetUrl' => false,
            'imgType' => ImgUrl::APPTYPE_APP,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE,
        ]);
        if ($albumId && $data['publish_time_int'] < time()) {
            $form->datetime('publish_time', '发布时间')->width('200px')->disable();
        } else {
            $form->datetime('publish_time', '发布时间')->width('200px')->help('发布时间要晚于当前十分钟,不填则默认当前时间');
        }

        $form->tags('tag_list', '标签')->options($tagList);
        if($albumId){
            $form->table('wiki_list', '商品列表', function ($table) {
                $table->text('wiki_id')->placeholder('商品id');
                $table->textarea('goods_name')->disable();
                $table->textarea('content')->placeholder('推荐语（不超过200字）');
                $table->text('obj_id')->placeholder('内容ID');
            });
        }else {
            $form->table('wiki_list', '商品列表', function ($table) {
                $table->text('wiki_id')->placeholder('商品id');
                $table->textarea('content')->placeholder('推荐语（不超过200字）');
                $table->text('obj_id')->placeholder('内容ID');
            });
        }
        $form->confirm('确定提交吗？', 'add');
        $form->action('/admin/album/index/save');

        $tab = new Tab();
        $tab->add($title, $form->render(), true);
        $tab->addLink('官方清单管理', url("/admin/album/index"), false);
        $content->row($tab);

        return $content
            ->header("发现好物 | $title")
            ->description(' ')
            ->breadcrumb(['text' => '官方清单管理', 'url' => '/album/index/'], ['text' => $title]);
    }

    public function save(Request $request): RedirectResponse
    {
        $albumId = $request->input('album_id', '');//清单id
        $title = $request->input('title', 0);//清单名称
        $desc = $request->input('desc', '');//清单描述
        $coverImg = $request->input('cover_img', '');//清单封面图
        $publishTime = $request->input('publish_time', '');//发布时间
        $wikList = $request->input('wiki_list', []);//商品列表
        $tagList = array_filter($request->input('tag_list', []));//标签列表
        $uid = $request->input('uid', '');//标签列表
        $wikList = array_values((FineGoodsService::arrayFilterFieldValue($wikList, '_remove_', 0)));
        try {
            if (empty($uid)) {
                throw new Exception('官方清单uid不可缺失');
            }
            if (mb_strlen($title, 'utf8') > 20) {
                throw new Exception('清单名称（最多可输入20个字）');
            }
            if (mb_strlen($desc, 'utf8') > 1000) {
                throw new Exception('清单描述（最多支持配置1000字）');
            }
            if ($coverImg == '') {
                throw new Exception('清单封面图不可为空');
            }

            if (empty($wikList)) {
                throw new Exception('商品列表不可为空');
            } else {
                $wikiIdArr = array_column($wikList, 'wiki_id');
                $wikiInfoList = mWiki::getInfosByWikiIds($wikiIdArr);
                if(count($wikiInfoList) > AlbumListModel::ALBUM_WIKI_LIMIT){
                    throw new Exception('商品列表最多添加50个');
                }
                foreach ($wikList as $wikiInfo) {
                    if (!isset($wikiInfoList[$wikiInfo['wiki_id']])) {
                        throw new Exception('商品id:'.$wikiInfo['wiki_id'].'不可用');
                    }
                    if (mb_strlen($wikiInfo['content'], 'utf8') > 200) {
                        throw new Exception('商品id:'.$wikiInfo['wiki_id'].'-推荐语（最多支持配置200字）');
                    }
                }
            }

            if ($publishTime) {
                $publishTime = strtotime(date('Y-m-d H:i', strtotime($publishTime))); //最小时间粒度为分钟
                if ($publishTime < (time() + 600)) {
                    throw new Exception('发布时间要晚于当前十分钟');
                }
            } else {
                $publishTime = 0; //如果没有选择发布时间 或者已经过了发布时间 则此时发布时间不能修改 所有也是0
            }
            $preg = "/http[s]?:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is";
            if(preg_match($preg,$coverImg)){
                $coverImg = $coverImg;
            }else{
                $coverImg = $coverImg ? ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $coverImg,ImgUrl::IMAGE_SIZE_ORI_NPHONE) : '';
            }
            $data = [
                'title' => $title,
                'desc' => $desc,
                'cover_img' => $coverImg,
                'publish_time' => $publishTime,
                'wiki_list' => $wikList,
                'tag_list' => $tagList,
            ];
            $data['uid'] = $uid;
            $data['admin_id'] = Admin::user()->id;
            $result = AlbumListService::saveAlbumData($data, $albumId);
            if (!$result) {
                throw new Exception('活动编辑失败');
            }

            return redirect('/admin/album/index');
        } catch (Exception $e) {
            Log::error('活动编辑失败', $e->getMessage());
            $error = new MessageBag([
                'title' => '编辑失败,'.$e->getMessage(),
            ]);

            return back()->with(compact('error'));
        }

    }

    public function act(Request $request)
    {
        $albumId = $request->input('album_id', 0);
        $act = $request->input('act', '');
        $code = 1;
        $key = redisKeys::KEY_B_CACHE_ALBUM_RECOMMEND_OFFICIAL_LIST;
        try {
            switch ($act) {
                case 'self-visible';
                    //先查询是否在推荐清单里面 如果在推荐清单里面 则要先进行更换 再修改状态
                    $redis = new newCache($key);
                    $aData = $redis->getCache();
                    $albumIdCacheArr = $aData ? explode(',', $aData):[];

//                    $albumIdCacheArr = AlbumRecommendCache::getData();
                    if (in_array($albumId, $albumIdCacheArr)) {
                        $code = 0;
                        $msg = '请先把当前清单移除推荐清单列表之后再操作';
                    } else {
                        AlbumListModel::updateDataByWhere(['status' => AlbumListModel::STATUS_USER_PRIVATE , 'admin_id' => Admin::user()->id],
                            ['album_id' => $albumId]);
                        $msg = '已修改为仅自己可见';
                    }
                    break;
                case 'all-public';
                    AlbumListModel::updateDataByWhere(['status' => AlbumListModel::STATUS_SUCCESS , 'admin_id' => Admin::user()->id],
                        ['album_id' => $albumId]);
                    $msg = '已修改为全员可见';
                    break;
                case 'del-album';
                    //先查询是否在推荐清单里面 如果在推荐清单里面 则要先进行更换 再修改状态
                    $redis = new newCache($key);
                    $aData = $redis->getCache();
                    $albumIdCacheArr = $aData ? explode(',', $aData):[];
                    if (in_array($albumId, $albumIdCacheArr)) {
                        $code = 0;
                        $msg = '请先把当前清单移除推荐清单列表之后再操作';
                    } else {
                        $uid = IdParse::getUid($albumId);
                        $adminId = Admin::user()->id;
                        $result = AlbumListService::delAlbum($albumId , $uid , $adminId);
                        if($result){
                            $msg = '后台操作删除成功';
                        }else{
                            $msg = '后台操作删除失败';
                        }
                    }
                    break;
                default;
                    $msg = 'nothing ';


            }
        } catch (\Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }

        $response = [
            'code' => $code,
            'msg' => $msg,
        ];

        return response()->json($response);
    }
}
